<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="user-info">
        <span class="username">{{ otherUserName }}</span>
      </div>
    </div>
    
    <!-- 重构聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <template v-else>
        <!-- 加载更多按钮 -->
        <div v-if="hasMoreMessages" class="load-more" @click="loadMoreMessages">
          <span>加载更多消息</span>
        </div>
        
        <!-- 重构消息列表 -->
        <div v-for="(message, index) in messages" :key="message.messageID" class="message-wrapper">
          <!-- 日期分隔线 -->
          <div v-if="showDateDivider(message, index)" class="date-divider">
            <span>{{ formatDateDivider(message.sendTime) }}</span>
          </div>
          
          <!-- 重构消息气泡 -->
          <div class="message-row" :class="{ 'message-self': message.senderID == currentUserId }">
            <!-- 头像 -->
            <div class="avatar-container">
              <img class="avatar" :src="message.senderID == currentUserId ? currentUserAvatar : otherUserAvatar" alt="头像" />
            </div>
            
            <!-- 消息内容 -->
            <div class="bubble-container">
              <div class="bubble">
                <span class="text">{{ message.content }}</span>
              </div>
              <div class="time">{{ formatMessageTime(message.sendTime) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 无消息提示 -->
        <div v-if="messages.length === 0" class="empty-messages">
          <el-empty description="暂无消息" />
        </div>
      </template>
    </div>
    
    <!-- 消息输入区域 -->
    <div class="chat-input">
      <textarea 
        v-model="messageText" 
        placeholder="输入消息..." 
        @keyup.enter="sendMessage"
        class="message-textarea"
      ></textarea>
      <div class="send-button" @click="sendMessage" :class="{ 'disabled': !messageText.trim() }">
        发送
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import UserUtil from '@/utils/User/User.js';
import { ElMessage } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();
const messagesContainer = ref(null);

// 聊天相关数据
const chatSessionID = ref(null);
const otherUserID = ref(null);
const currentUserId = computed(() => UserUtil.getUserId());
const otherUserName = ref('对方用户');
const otherUserAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png');
const currentUserAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png');
const messages = ref([]);
const messageText = ref('');
const loading = ref(true);
const currentPage = ref(1);
const pageSize = ref(20);
const totalMessages = ref(0);
const hasMoreMessages = computed(() => messages.value.length < totalMessages.value);

// 获取当前用户头像
const fetchCurrentUserAvatar = async () => {
  try {
    const userInfo = await UserProfileApi.getUserInfo(currentUserId.value);
    currentUserAvatar.value = userInfo.headshot || currentUserAvatar.value;
  } catch (error) {
    console.error('获取当前用户头像失败:', error);
  }
};

// 获取对方用户信息
const fetchOtherUserInfo = async () => {
  try {
    const userInfo = await UserProfileApi.getUserInfo(otherUserID.value);
    otherUserName.value = userInfo.username || '对方用户';
    otherUserAvatar.value = userInfo.headshot || otherUserAvatar.value;
  } catch (error) {
    console.error('获取对方用户信息失败:', error);
  }
};

// 获取聊天消息
const fetchMessages = async (page = 1, append = false) => {
  try {
    loading.value = true;
    const response = await UserProfileApi.getChatMessages(chatSessionID.value, page, pageSize.value);
    
    
    // 解析响应数据
    let parsedResponse;
    if (typeof response === 'string') {
      parsedResponse = JSON.parse(response);
    } else {
      parsedResponse = response;
    }
    console.log('response', parsedResponse);
    // 更新总消息数
    totalMessages.value = parsedResponse.totalMessages;
    
    // 确保messages是数组
    const messagesList = Array.isArray(parsedResponse.messages) ? parsedResponse.messages : [];
    
    // 更新消息列表
    if (append) {
      messages.value = [...messagesList.reverse(), ...messages.value];
    } else {
      messages.value = messagesList.reverse();
    }
    
    // 标记消息为已读
    if (messages.value.length > 0) {
      try {
        await UserProfileApi.markMessagesAsRead(chatSessionID.value, currentUserId.value);
      } catch (error) {
        console.error('标记消息为已读失败:', error);
      }
    }
    
    // 如果是第一次加载或者不是加载更多，滚动到底部
    if (page === 1 && !append) {
      await nextTick();
      scrollToBottom();
    }
  } catch (error) {
    console.error('获取聊天消息失败:', error);
    ElMessage.error(`获取聊天消息失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 加载更多消息
const loadMoreMessages = async () => {
  if (loading.value || !hasMoreMessages.value) return;
  
  currentPage.value++;
  await fetchMessages(currentPage.value, true);
};

// 发送消息
const sendMessage = async () => {
  if (!messageText.value.trim()) return;
  
  try {
    await UserProfileApi.sendMessage(
      chatSessionID.value,
      currentUserId.value,
      messageText.value
    );
    
    // 清空输入框
    messageText.value = '';
    
    // 重新获取最新消息
    await fetchMessages(1);
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error(`发送消息失败: ${error.message || '未知错误'}`);
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 格式化消息时间
const formatMessageTime = (timeString) => {
  if (!timeString) return '';
  
  const date = new Date(timeString);
  return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化日期分隔线
const formatDateDivider = (timeString) => {
  if (!timeString) return '';
  
  const date = new Date(timeString);
  const now = new Date();
  const diff = now - date;
  
  // 今天
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return '今天';
  }
  
  // 昨天
  if (diff < 48 * 60 * 60 * 1000 && date.getDate() === now.getDate() - 1) {
    return '昨天';
  }
  
  // 一周内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return weekdays[date.getDay()];
  }
  
  // 更早
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 判断是否显示日期分隔线
const showDateDivider = (message, index) => {
  if (index === 0) return true;
  
  const currentDate = new Date(message.sendTime);
  const prevDate = new Date(messages.value[index - 1].sendTime);
  
  return currentDate.getDate() !== prevDate.getDate() || 
         currentDate.getMonth() !== prevDate.getMonth() || 
         currentDate.getFullYear() !== prevDate.getFullYear();
};

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.chatSessionID && newQuery.otherUserID) {
    chatSessionID.value = newQuery.chatSessionID;
    otherUserID.value = newQuery.otherUserID;
    
    // 重置数据
    messages.value = [];
    currentPage.value = 1;
    loading.value = true;
    
    // 获取数据
    fetchOtherUserInfo();
    fetchMessages(1);
  }
}, { immediate: true });

onMounted(async () => {
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  // 获取当前用户头像
  await fetchCurrentUserAvatar();
  
  // 从路由参数获取聊天室ID和对方用户ID
  if (route.query.chatSessionID && route.query.otherUserID) {
    chatSessionID.value = route.query.chatSessionID;
    otherUserID.value = route.query.otherUserID;
    
    // 获取对方用户信息
    await fetchOtherUserInfo();
    
    // 获取聊天消息
    await fetchMessages(1);
  }
});
</script>

<style lang="less" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 144px);
  background-color: #f5f5f5;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;

  .chat-header {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    z-index: 10;
    
    .back-button {
      margin-right: 15px;
      cursor: pointer;
      font-size: 20px;
    }
    
    .user-info {
      flex: 1;
      
      .username {
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    
    .loading-container {
      padding: 20px;
    }
    
    .load-more {
      text-align: center;
      padding: 10px;
      color: #1890ff;
      cursor: pointer;
      
      &:hover {
        background-color: rgba(24, 144, 255, 0.1);
      }
    }
    
    .date-divider {
      text-align: center;
      margin: 15px 0;
      
      span {
        display: inline-block;
        padding: 5px 10px;
        background-color: rgba(0, 0, 0, 0.1);
        border-radius: 10px;
        font-size: 12px;
        color: #666;
      }
    }
    
    .message-wrapper {
      margin-bottom: 15px;
    }
    
    .message-row {
      display: flex;
      align-items: flex-start;
      margin-bottom: 10px;
      width: 100%;
      
      &.message-self {
        flex-direction: row-reverse;
        
        .avatar-container {
          margin-left: 10px;
          margin-right: 0;
        }
        
        .bubble-container {
          align-items: flex-end;
          display: flex;
          flex-direction: column;
          
          .bubble {
            background-color: #1890ff;
            color: white;
            border-radius: 15px 0 15px 15px;
            max-width: 100%;
            word-break: break-all;
          }
        }
      }
      
      .avatar-container {
        width: 40px;
        height: 40px;
        margin-right: 10px;
        flex-shrink: 0;
        
        .avatar {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
      }
      
      .bubble-container {
        display: flex;
        flex-direction: column;
        max-width: 60%;
        flex: 0 1 auto;
        
        .bubble {
          padding: 10px 15px;
          background-color: white;
          border-radius: 0 15px 15px 15px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
          display: inline-block;
          max-width: 100%;
          box-sizing: border-box;
          
          .text {
            word-wrap: break-word;
            white-space: pre-wrap;
            word-break: break-all;
            overflow-wrap: break-word;
            display: inline;
            font-size: 14px;
            line-height: 1.5;
          }
        }
        
        .time {
          margin-top: 5px;
          font-size: 12px;
          color: #999;
          align-self: flex-end;
        }
      }
    }
    
    .empty-messages {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
    }
  }
  
  .chat-input {
    display: flex;
    padding: 15px;
    background-color: white;
    border-top: 1px solid #eee;
    
    .message-textarea {
      flex: 1;
      height: 40px;
      max-height: 100px;
      padding: 10px 15px;
      border: 1px solid #ddd;
      border-radius: 20px;
      resize: none;
      outline: none;
      
      &:focus {
        border-color: #1890ff;
      }
    }
    
    .send-button {
      margin-left: 10px;
      padding: 0 20px;
      height: 40px;
      line-height: 40px;
      background-color: #1890ff;
      color: white;
      border-radius: 20px;
      cursor: pointer;
      
      &:hover {
        background-color: #40a9ff;
      }
      
      &.disabled {
        background-color: #ccc;
        cursor: not-allowed;
      }
    }
  }
}
</style>